import { ShapeFlag } from "../../flags"
import { createVNode } from ".."
import type { ComponentInstance, SetupContext, vnode } from "../../../types"


const PublicInstanceProxyHandler:ProxyHandler<ComponentInstance> = {
  get(target, p, receiver) {
    const { accessCache, setupReturnState, data, props } = target


  },
  set(target, p, newValue, receiver) {
    const { setupReturnState, data, props } = target

    return true   
  },
  has(target, p) {
    const { 
      accessCache, 
      data, 
      setupReturnState, 
      props, 
      ctx,
      appContext
    } = target

    return true
  }
}


function initProps(instance:ComponentInstance) {}
function initSlots(instance:ComponentInstance) {}
function initProxy(instance:ComponentInstance) {
  instance.proxy = new Proxy(instance.ctx!, PublicInstanceProxyHandler)
}


function createSetupContext(instance:ComponentInstance): SetupContext {
  return {
    attrs: instance.attrs!,
    slots: instance.slots!,
    emit: instance.emit!,
  }
}

function handleSetupResult(instance:ComponentInstance, result:object|Function) {
  if(typeof result === 'function') {
    instance.render = result as any
  } else {
    instance.setupReturnState = result
  }
}

function normalizeRenderResult(result:unknown):vnode {
  return createVNode()
}

function finishComponentSetup(instance:ComponentInstance) {
  if(!instance.render) {
    const { render } = instance.type
    instance.render = render
  }

  const subTree = normalizeRenderResult(instance.render())


}

export function setupComponent(instance:ComponentInstance) {
  const { tag, props, children, shapeFlag } = instance.vnode
  const { setup, render } = instance.type

  const isStateful = !!shapeFlag && shapeFlag === ShapeFlag.STATEFUL_COMPONENT

  initProps(instance)
  initSlots(instance)

  const context: SetupContext = createSetupContext(instance)

  window.currentInstance = instance

  if(setup && isStateful) {
    handleSetupResult(instance, setup(props, context))
  }

  window.currentInstance = null

  initProxy(instance)

  finishComponentSetup(instance)
}
